//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Windows.Forms;
using Dundas.Charting.WinControl;
using Microsoft.Research.eResearch;

namespace TridentAPI
{
    /// <summary>
    /// Render Dundas Chart control in Windows Form
    /// </summary>
    public class DundasChart
    {
        private Form form;
        private Chart chart;

        public void Show(DataProduct dp, string chartType, string title, int height, int width)
        {
            form = new Form();
            form.Width = width;
            form.Height = height;
            form.Text = title;

            // Write byte array to a temp XML file and use XML to generate a DataTable
            byte[] content = dp.Contents;
            string tempFile = Path.GetTempFileName();
            File.WriteAllBytes(tempFile, content);
            DataTable dataTable = new DataTable();
            dataTable.ReadXml(tempFile);
            File.Delete(tempFile);

            chart = new Chart();
            ChartArea chartArea = new ChartArea();
            chart.ChartAreas.Add(chartArea);
            DataView dataView = new DataView(dataTable);
            chart.DataBindTable(dataView);
            
            chart.Dock = DockStyle.Fill;
            form.Controls.AddRange(new Control[] { chart });

            ComboBox cbChartType = new ComboBox();
            cbChartType.DataSource = Enum.GetValues(typeof(SeriesChartType));
            
            cbChartType.TextChanged += new EventHandler(ChartType_TextChanged);
            cbChartType.Dock = DockStyle.Bottom;
            form.Controls.AddRange(new Control[] { cbChartType });
            
            form.Show();

            int index = cbChartType.FindString(chartType);
            cbChartType.SelectedIndex = index;
        }

        void ChartType_TextChanged(object sender, EventArgs e)
        {
            foreach (Series series in chart.Series)
            {
                series.BorderWidth = 3;
                series.Type = (SeriesChartType)Enum.Parse(typeof(SeriesChartType),
                    ((ComboBox)sender).Text, true);
            }
        }
    }
}
